package com.gp.pj.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * @author 45709
 */
public class JWTUtils {

    public static final String SIGN = "1013TUtianrui**";

    /**
     * 生成token
     */
    public static String getToken(Map<String,Object> map){
        Calendar instance = Calendar.getInstance();
        //设置token过期时间为30分钟
        instance.add(Calendar.MINUTE,30);

        JWTCreator.Builder builder = JWT.create();

        map.forEach((key,val)-> builder.withClaim(key, String.valueOf(val)));
        String token = "";
        try{
            token = builder.withExpiresAt(instance.getTime())
                    .sign(Algorithm.HMAC256(SIGN));
        }catch (Exception e){
            e.printStackTrace();
        }

        return token;
    }

    public static void verify(String token){
        JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

    /**
     * 获取token中的payload
     */
    public static DecodedJWT verifyToekn(String token){
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }
}
